#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include "Defines.h"
#include "WebInterface/WebInterface.h"
#include "Parsing/Parsing.h"
#include "SQLInterface/SQLInterface.h"

static char* const FILE_PREFIX = "Temp/";
static char* const FILE_SUFFIX = ".html";
static char* const URL_PREFIX = "http://finance.yahoo.com/q/hp?s=";
// arbitrary dates ftw (this code will not work for stocks with data prior to 1900 or after 2050)
// if you're still using this in 2050 you're doing something horribly wrong.
static char* const URL_SUFFIX = "&a=03&b=12&c=1900&d=02&e=28&f=2050&g=d&z=66&y="; 

static char* const NYSE = "NYSE";

static char InitialPopulateCurrentFileName[100];

result_type download_yahoo_to_temp(const char* const symbol, const int tableIndex);

int main()
{
    char** symbolList = NULL;
    char** nameList = NULL;
    int length = 0;
    int result;
    node_t* list;
    node_t* temp;
    tuple_t* tuple;
    int i, i2;
    char* exchangeId;

    list = init_list(NULL);
    // TODO: add symbol list download/update
    
    // parse symbol list
    result = parse_symbols_names(&symbolList, &length, &nameList); //assumes eoddata format...

    if(result != SUCCESS)
    {
        return 1;
    }

    // Insert Exchange
    tuple = initTuple(TABLE_EXCHANGE);
    tuple->params[EXCHANGE_PARAM_ID] = malloc(sizeof(char) * 2);
    strcpy(tuple->params[EXCHANGE_PARAM_ID], "0"); //filler
    tuple->params[EXCHANGE_PARAM_NAME] = malloc(sizeof(char) * strlen(NYSE));
    strcpy(tuple->params[EXCHANGE_PARAM_NAME], NYSE);
    if(SQL_insert(tuple) != SUCCESS)
    {
        return 1;
    }

    // get NYSE id
    tuple = initTuple(TABLE_EXCHANGE);
    tuple->params[EXCHANGE_PARAM_NAME] = malloc(sizeof(char) * strlen(NYSE));
    strcpy(tuple->params[EXCHANGE_PARAM_NAME], NYSE);
    list = SQL_select(tuple); // this list needs to be freed
    if(list && list->element)
    {
        exchangeId = (char*)malloc(strlen((char*)(((tuple_t*)(list->element))->params[EXCHANGE_PARAM_ID])) + 1);
        strcpy(exchangeId, (char*)(((tuple_t*)(list->element))->params[EXCHANGE_PARAM_ID]));
    }
    else
    {
        return 1;
    }

    list = init_list(NULL);
    for(i = 0; i < length; i++)
    {
        printf("Downloading data for %s...\n", symbolList[i]);

        // insert into stock table
        tuple = initTuple(TABLE_STOCK);
        tuple->params[STOCK_PARAM_SYMBOL] = malloc((strlen(symbolList[i]) + 1) * sizeof(char));
        tuple->params[STOCK_PARAM_EXCHANGE_ID] = malloc((strlen(exchangeId) + 1) * sizeof(char));
        tuple->params[STOCK_PARAM_NAME] = malloc((strlen(nameList[i]) + 1) * sizeof(char));
        strcpy(tuple->params[STOCK_PARAM_SYMBOL], symbolList[i]);
        strcpy(tuple->params[STOCK_PARAM_EXCHANGE_ID], exchangeId);
        strcpy(tuple->params[STOCK_PARAM_NAME], nameList[i]);
        if(SQL_insert(tuple) != SUCCESS)
        {
            printf("Error inserting stock into stock table.\n\n");
            continue;
        }

        result = SUCCESS;
        for(i2 = 0; result == SUCCESS; i2 += TUPLES_PER_HTML_PAGE)
        {
            result = download_yahoo_to_temp(symbolList[i],i2);
            if(result != SUCCESS)
            {
                printf("Failure downloading...");
                break;
            }
            result = parse_html_table(InitialPopulateCurrentFileName, list, symbolList[i]);
        }
        
        if(result == END_OF_DATA)
        {
            printf("Uploading to database...\n");
            // first node was empty so skip and free
            temp = list;
            list = list->next;
            free(temp);

            result = SQL_insert_list(list);
            list = init_list(NULL);

            if(result == SUCCESS)
            {
                printf("Success!!!\n\n");
            }
            else
            {
                printf("***FAILURE***\n\n");
            }
        }
        else
        {
            printf("Finished with parsing error!!!\n\n");
        }
    
    }
    return 0;
}

result_type download_yahoo_to_temp(const char* const symbol, const int tableIndex)
{
    char url[100]; // TODO: #define these values or something...
    result_type result = SUCCESS;
    int tryCount = 0;

    do
    {
        // set filename
        sprintf(InitialPopulateCurrentFileName,"%s%s%d%s",
                FILE_PREFIX, symbol, tableIndex, FILE_SUFFIX);

        // set url
        sprintf(url,"%s%s%s%d", URL_PREFIX, symbol, URL_SUFFIX, tableIndex);

        result = download_file(url, InitialPopulateCurrentFileName);
        tryCount++;

    }while(result == CONNECTION_ERROR && tryCount < 5);

    return result;
}

